<script lang="ts" setup>
import type { CheckedSelect } from '#/api';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElOption, ElSelect } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { addUser, editUser, postSelect, roleSelect } from '#/api/user/sysuser';
import { $t } from '#/locales';

import { formSchema } from '../data';

const emit = defineEmits(['success']);

const roles = ref<CheckedSelect>({ checkedKeys: [], selects: [] });
const posts = ref<CheckedSelect>({ checkedKeys: [], selects: [] });

const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  schema: formSchema(),
  wrapperClass: 'grid-cols-2 gap-x-4',
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    const data = await formApi.getValues();
    data.roleIds = roles.value.checkedKeys;
    data.postIds = posts.value.checkedKeys;

    try {
      await (data?.userId ? editUser(data) : addUser(data));
      modalApi.close();
      emit('success');
    } finally {
      modalApi.lock(false);
    }
  },
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData();
    modalApi.setState({
      title: data?.userId
        ? $t('ui.actionTitle.edit', [$t('user.sysuser')])
        : $t('ui.actionTitle.create', [$t('user.sysuser')]),
    });
    formApi.setValues(data, false);
    roles.value = await roleSelect(data?.userId);
    posts.value = await postSelect(data?.userId);
  },
});
</script>

<template>
  <Modal class="w-full max-w-[700px]">
    <Form class="mx-4">
      <template #roleIds>
        <ElSelect class="w-full" v-model="roles.checkedKeys" multiple>
          <ElOption
            v-for="item in roles?.selects"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </ElSelect>
      </template>
      <template #postIds>
        <ElSelect class="w-full" v-model="posts.checkedKeys" multiple>
          <ElOption
            v-for="item in posts?.selects"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </ElSelect>
      </template>
    </Form>
  </Modal>
</template>
